package com.peakproducts;

import java.util.Hashtable;

import org.json.me.JSONArray;
import org.json.me.JSONObject;
import org.json.me.util.Utils;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.RadioButtonField;
import net.rim.device.api.ui.component.RadioButtonGroup;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.container.HorizontalFieldManager;

public class UpdateScreen extends PeakScreen {
	private ConnectionThread connThread;
	private JSONObject leadData;
	private UpdateFields updateFields = new UpdateFields();
	private Hashtable fieldsList;
	private BasicEditField comment = new BasicEditField("Comment:","");
	private RadioButtonField infoRadio = new RadioButtonField();
	private RadioButtonGroup rbGroup = new RadioButtonGroup();
	private int isModify = 0;
	private PeakField backBtn = new PeakField("Main Menu");
	private HorizontalFieldManager hrm = new HorizontalFieldManager();
	private FieldListener saveBtnEvent = new FieldListener();
	public UpdateScreen(ConnectionThread ct, JSONObject data) { 
		 this.connThread = ct;
		 leadData = data;
		 setTitle("Lead Manager - update lead");
		 try{
			 fieldsList = updateFields.getFieldList();
			 initFields(leadData.getJSONArray("nextscreen"));
		 }catch (Exception e) {
			// TODO: handle exception
			 Status.show("There are no next status.");
		}
	}
	private void initFields(JSONArray jsonArray) {
		if(jsonArray.length()>0){
			try{
				int currntStatus = leadData.getInt("leads_status");
				switch (currntStatus) {
					case 5:
					case 6:
					case 14:
					case 18:
					case 19:
					case 21:
					case 22:
					case 23:
					case 24:
					case 26:
					case 27:
					case 30:
						isModify = 1;
						infoRadio.setLabel("Change Current Lead Status Infomation - Current Status:"+leadData.getString("status_name"));
						add(infoRadio);
						rbGroup.add(infoRadio);
						try{
							int lead_id = leadData.getInt("leads_status");
							int fieldLength = Integer.parseInt((String)fieldsList.get(lead_id+"_length"));
							if(fieldLength!=-1){
								add((BasicEditField)fieldsList.get(lead_id+"_field"));
								for(int i=1;i<fieldLength;i++){
									add((BasicEditField)fieldsList.get(lead_id+"_field_"+i));
								}
							}
							//appointField.setText(leadData.getString("history_data"));
							//add(appointField);
						}catch (Exception e) {
							// TODO: handle exception
						}
						break;
				}
				for(int i=0;i<jsonArray.length();i++){
					add(new SeparatorField());
					String tmpKey = (String)jsonArray.get(i);
					RadioButtonField tmpField = (RadioButtonField) fieldsList.get(tmpKey);
					rbGroup.add(tmpField);
					add(tmpField);
					int fieldLength = Integer.parseInt((String)fieldsList.get(tmpKey+"_length"));
					//get other
					if(fieldLength!=-1){
						Object tmpDetails = fieldsList.get(tmpKey+"_field");
						if(tmpDetails instanceof BasicEditField){
							add((BasicEditField)tmpDetails);
						}else if(tmpDetails instanceof ObjectChoiceField){
							add((ObjectChoiceField)tmpDetails);
						}
						try{
							for(int j=1;j<fieldLength;j++){
								add((BasicEditField)fieldsList.get(tmpKey+"_field_"+j));
							}
						}catch (Exception e) {
							// TODO: handle exception
							Status.show("In here:"+e.getMessage());
						}
					}
				}
				add(new SeparatorField());
				add(comment);
				PeakField saveBtn = new PeakField("Save Change");
				add(new SeparatorField());
				hrm.add(saveBtn);
				hrm.add(backBtn);
				add(hrm);
				//init event
				saveBtn.setChangeListener(saveBtnEvent);
				backBtn.setChangeListener(saveBtnEvent);
			}catch (Exception e) {
				// TODO: handle exception
				Status.show("wrong type:"+e.getMessage());
			}
		}else{
			RichTextField noNextStatus = new RichTextField("Current lead has been completed, THANK YOU! ");
			add(noNextStatus);
			add(backBtn);
			backBtn.setChangeListener(saveBtnEvent);
		}
	}
	
	class FieldListener implements FieldChangeListener {
        public void fieldChanged(Field field, int context) {
        	if(!((PeakField)field).getLabel().equals("Main Menu"))
        	{
	        	int seleteIndex = rbGroup.getSelectedIndex();
	        	if(seleteIndex==-1)
	        	{
	        		Status.show("Please choose update type.");
	        	}else{
		            StringBuffer sb = new StringBuffer("Update...");
		            connThread.get(Utils.restURL+"/Lead/Update" + getFieldData());
		            while (connThread.sending) {
		                try {
		                    Status.show( sb.append(".").toString() );
		                    Thread.sleep(100);
		                } catch (InterruptedException e) {
		                    e.printStackTrace();
		                }
		            }
		
		            if (connThread.sendResult) {
		                Status.show("Transmission Successful");
		                parseResults( connThread.responseContent );
		            } else {
		                Status.show("Transmission Failed");
		            }
	        	}
        	}else{
        		//Status.show("Back to Search");
        		UiApplication.getUiApplication().pushScreen(new LeadSearchScreen(connThread));
        		close();
        	}
        }

		private void parseResults(String responseContent) {
			// TODO Auto-generated method stub
			//Status.show(responseContent);
			try{
				JSONObject result = new JSONObject(responseContent);
				if(result.getString("error").equals("0")){
					Dialog.inform("Store Success!");
				}else{
					Dialog.inform("Update lead failed. Error:"+result.getString("error"));
				}
			}catch (Exception e) {
				// TODO: handle exception
				Status.show("Update lead failed. "+e.getMessage());
			}
			LeadSearchScreen searchScreen = new LeadSearchScreen(connThread);
			UiApplication.getUiApplication().pushScreen(searchScreen);
			close();
		}
		
		private String getFieldData() {
			StringBuffer sb = new StringBuffer();
	        sb.append("/leadId/");
	        try{
		        sb.append(leadData.getString("id"));
		        int seleteIndex = rbGroup.getSelectedIndex();
		        JSONArray nextStatusList = leadData.getJSONArray("nextscreen");
		        String nextStatusId = leadData.getString("leads_status");
		        JSONObject postData = new JSONObject();
		        if(isModify==1)
		        {
		        	seleteIndex++;
		        	if(seleteIndex==1){
		        		nextStatusId = leadData.getString("leads_status");
		        		int fieldLength = Integer.parseInt((String)fieldsList.get(leadData.getString("leads_status")+"_length"));
		        		if(fieldLength!=-1){
		        			postData.put(nextStatusId+"_1", ((BasicEditField)fieldsList.get(leadData.getString("leads_status")+"_field")).getText());
							for(int i=1;i<fieldLength;i++){
								postData.put(leadData.getString("leads_status")+"_"+(i+1), ((BasicEditField)fieldsList.get(leadData.getString("leads_status")+"_field_"+i)).getText());
							}
		        		}
		        	}
		        	else
		        		nextStatusId = nextStatusList.getString(seleteIndex);
		        }else{
		        	nextStatusId = nextStatusList.getString(seleteIndex);
		        }
		        Object tmpDetails = fieldsList.get(nextStatusId+"_field");
		        int fieldLength = Integer.parseInt((String)fieldsList.get(nextStatusId+"_length"));
		        if(fieldLength!=-1){
			        for(int i=1;i<fieldLength;i++){
			        	BasicEditField tmpField = (BasicEditField)fieldsList.get(nextStatusId+"_field_"+i);
			        	postData.put(nextStatusId+"_"+(i+1), tmpField);
			        }
					if(tmpDetails instanceof BasicEditField){
						postData.put(nextStatusId+"_1", ((BasicEditField)tmpDetails).getText());
					}else if(tmpDetails instanceof ObjectChoiceField){
						int tmpSelectIndex = ((ObjectChoiceField)tmpDetails).getSelectedIndex();
						if(nextStatusId.equals("4"))
						{
							switch (tmpSelectIndex) {
							case 0:
								postData.put(nextStatusId+"_1", "1");
								break;
							case 1:
								postData.put(nextStatusId+"_1", "2");
								break;
							case 2:
								postData.put(nextStatusId+"_1", "8");
								break;
							case 3:
								postData.put(nextStatusId+"_1", "27");
								break;
							default:
								break;
							}
						}else if(nextStatusId.equals("9")){
							switch (tmpSelectIndex) {
							case 0:
								postData.put(nextStatusId+"_1", "3");
								break;
							case 1:
								postData.put(nextStatusId+"_1", "5");
								break;
							case 2:
								postData.put(nextStatusId+"_1", "6");
								break;
							case 3:
								postData.put(nextStatusId+"_1", "7");
								break;
							case 4:
								postData.put(nextStatusId+"_1", "9");
								break;
							case 5:
								postData.put(nextStatusId+"_1", "19");
								break;
							case 6:
								postData.put(nextStatusId+"_1", "20");
								break;
							case 7:
								postData.put(nextStatusId+"_1", "21");
								break;
							case 8:
								postData.put(nextStatusId+"_1", "22");
								break;
							case 9:
								postData.put(nextStatusId+"_1", "23");
								break;
							case 10:
								postData.put(nextStatusId+"_1", "24");
								break;
							case 11:
								postData.put(nextStatusId+"_1", "25");
								break;
							case 12:
								postData.put(nextStatusId+"_1", "26");
								break;
							case 13:
								postData.put(nextStatusId+"_1", "28");
								break;
							default:
								break;
							}
						}
					}
				}
		        //-------------------------------------------------------------------------------
		        sb.append("/currentstatus/");
		        sb.append(leadData.getString("leads_status"));
		        sb.append("/userid/");
		        sb.append(Utils.contractor_id);
		        sb.append("/currentstatusname/");
		        sb.append(HURLEncoder.URLEncode(leadData.getString("status_name")));
		        sb.append("/newstatus/");
		        sb.append(nextStatusId);
		        sb.append("/interestid/");
		        sb.append(leadData.getString("interest_id"));
		        sb.append("/postdata/");
		        sb.append(HURLEncoder.URLEncode(postData.toString()));
		        sb.append("/comment/");
		        sb.append(HURLEncoder.URLEncode(comment.getText()));
	        }catch (Exception e) {
				// TODO: handle exception
	        	Status.show("Error when get Data:"+e.getMessage());
			}
	        return sb.toString();
		}
    }
}
